import 'dart:io';
import 'dart:typed_data';

import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/event_bus.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:flutter/material.dart';
import 'package:gesture_zoom_box/gesture_zoom_box.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_pickers/CropConfig.dart';
import 'package:image_pickers/Media.dart';
import 'package:image_pickers/UIConfig.dart';
import 'package:image_pickers/image_pickers.dart';

class MineModAvatarPage extends StatefulWidget {

  final String avatar;

  MineModAvatarPage({Key key, this.avatar}) : super(key: key);

  @override
  _MineModAvatarPageState createState() => _MineModAvatarPageState();
}

class _MineModAvatarPageState extends State<MineModAvatarPage> {

  File _fileImage;

  bool isupdate = false;

  GlobalKey _scaffoldKey = GlobalKey<ScaffoldState>();

  _save() {
    Networktool.downloadImage(widget.avatar, success: (data) {
      _saveImage(data);
    });
  }

  _photo() async {
    // final size = MediaQuery.of(context).size;
    // var image = await ImagePicker.pickImage(source: ImageSource.camera, imageQuality: 90, maxHeight: size.width);
    // if(image != null){
    //   _uploadImage(image);
    // }

    List<Media> _listImagePaths = await ImagePickers.pickerPaths(
      galleryMode: GalleryMode.image,
      selectCount: 1,
      showCamera: true,
      // compressSize: 500,
      cropConfig :CropConfig(enableCrop: true,height: 1,width: 1),
    );
    if(_listImagePaths != null) {
      _uploadImage(File(_listImagePaths.first.path));
    }
  }

  _album() async {
    // final size = MediaQuery.of(context).size;
    // var image = await ImagePicker.pickImage(source: ImageSource.gallery, imageQuality: 90,maxHeight: size.width);
    // if(image != null){
    //   _uploadImage(image);
    // }
    List<Media> _listImagePaths = await ImagePickers.pickerPaths(
      galleryMode: GalleryMode.image,
      selectCount: 1,
      showCamera: false,
      // compressSize: 500,
      uiConfig: UIConfig(uiThemeColor: APP_main_color),
      cropConfig :CropConfig(enableCrop: true,height: 1,width: 1),
    );

    if(_listImagePaths != null) {
      _uploadImage(File(_listImagePaths.first.path));
    }
  }

  

  _saveImage(dynamic data) async {
    final result = await ImageGallerySaver.saveImage(Uint8List.fromList(data));
    if(result != null) {
      AlertTool.showToast("保存成功");
    } else {
      AlertTool.showToast("保存失败,请检查相册权限是否开启");
    }
    print(result);
  }



  _uploadImage(File image) {
    AlertTool.showLoadingDialog(context,"正在上传...");
    Networktool.uploadImage(API.avatar, image, (data) async {
      print("$data");
      if(data["data"] != null) {
        SharedUserInfo.saveData(data, isupdateIM: true);
        isupdate = true;
        EventMineBus.instance.commit(EventMineKeys.UpdateMineInfo, null);
        setState(() {
          _fileImage = image;
        });
      }
    },
    fail: (msg) => AlertTool.showToast(msg),
    finaly: () => Navigator.of(context).pop()
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      key: _scaffoldKey,
      appBar: AppBar(
        backgroundColor: Colors.black,
        title: Text("个人头像", style: instanceTextStyle(17, Colors.white),),
        leading: IconButton(
          icon: Image.asset("assets/fanhui1.png"),
          onPressed: () => Navigator.of(context).pop(isupdate),
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.more_horiz, color: Colors.white,),
            onPressed: () {
              AlertTool.showBottomDialog(context, ["拍照", "从手机相册选择", "保存到手机"], onTapIndex: (index){
                switch (index) {
                  case 0:
                    _photo();
                    break;
                  case 1:
                    _album();
                    break;
                  case 2:
                    _save();
                    break;
                }
                Navigator.of(context).pop();
              });
            },
          )
        ],
      ),
      body: SafeArea(
        child: Center(
          child: _ImageWidget(avatar: widget.avatar,fileImage: _fileImage,),
        ),
      ),
    );
  }
}

class _ImageWidget extends StatefulWidget {

  final String avatar;
  final File fileImage;
  

  const _ImageWidget({Key key, this.avatar, this.fileImage}) : super(key: key);

  @override
  __ImageWidgetState createState() => __ImageWidgetState();
}

class __ImageWidgetState extends State<_ImageWidget> {

  @override
  Widget build(BuildContext context) {
    Widget wid = widget.fileImage == null ? FadeInImage.assetNetwork(
        placeholder: 'assets/head.jpg',
        image: widget.avatar ?? "",
        fit: BoxFit.fitWidth,
    ) : Image.file(widget.fileImage, fit: BoxFit.fitWidth,);

    return GestureZoomBox(
        maxScale: 5.0,
        doubleTapScale: 2.0,
        duration: Duration(milliseconds: 200),
        // onPressed: () => Navigator.pop(context),
        child: wid,
    );
  }
}